﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Streaming_Service.SQL_Ting {
    using System.Data;

    using Streaming_Service.Media;
    using Streaming_Service.User;

    public class RentQueries {
        public static bool RentMovie(int userId, int movieId, bool hd, SqlHandler sh) {
            if (!UserQueries.UserExists(userId, sh)) return false;
            if (!MovieQueries.MovieExists(movieId, sh)) return false;
            if (ActiveRent(userId, movieId, hd, sh)) return true;

            var SQL = "INSERT INTO rental (userid, movieid, rentdate, seendate, price, hd) "
            + "VALUES(@uid, @mid, @rentdate, @seendate, @price, @hd)";

            var c = sh.CreateCommand(SQL);
            c.Parameters.Add("uid", SqlDbType.Int).Value = userId;
            c.Parameters.Add("mid", SqlDbType.Int).Value = movieId;
            c.Parameters.Add("rentdate", SqlDbType.DateTime).Value = DateTime.Now;
            c.Parameters.Add("seendate", SqlDbType.DateTime).Value = DateTime.Now.AddDays(2);
            c.Parameters.Add("price", SqlDbType.Decimal).Value = hd
                                                                     ? PricingQueries.GetHdPrice(movieId, sh)
                                                                     : PricingQueries.GetSdPrice(movieId, sh);
            c.Parameters.Add("hd", SqlDbType.TinyInt).Value = hd ? 1 : 0;

            var r = c.ExecuteNonQuery();

            return r > 0;
        }

        public static List<RentSession> UserRents(int userId, bool onlyActive, SqlHandler sh) {
            var SQL = "SELECT "
                    + "mov.*, gen.id AS genreid, gen.name AS genrename, "
                    + "rental.movieid AS rentalmovieid, rental.rentdate, rental.seendate, rental.price AS rentalprice, rental.hd AS rentalhd "
                + "FROM rental, movie AS mov "
                + "LEFT JOIN moviegenre AS mg ON mov.id = mg.movieid "
                + "LEFT JOIN genre AS gen ON gen.id = mg.genreid "
                + "WHERE rental.userid = @uid AND rental.movieid = mov.id "
                + (onlyActive ? "AND rental.seendate >= GETDATE()" : "")
                + "ORDER BY rental.rentdate DESC";

            var sessions = new Dictionary<string, RentSession>();

            var c = sh.CreateCommand(SQL);
            c.Parameters.Add("uid", SqlDbType.Int).Value = userId;

            var r = c.ExecuteReader();
            while (r.Read()) {
                var rentalid = "r_" + r.GetInt32(r.GetOrdinal("rentalmovieid")) + "_" + userId + "_" + r.GetDateTime(r.GetOrdinal("rentdate")).ToLongDateString();
                if (!sessions.ContainsKey(rentalid)) {
                    var session = new RentSession();
                    session.UserId = userId;
                    session.Movie = MovieQueries.GetMovieEntry(r);
                    session.Price = r.GetDecimal(r.GetOrdinal("rentalprice"));
                    session.SessionStart = r.GetDateTime(r.GetOrdinal("rentdate"));
                    session.SessionEnd = r.GetDateTime(r.GetOrdinal("seendate"));
                    session.HD = r.GetByte(r.GetOrdinal("rentalhd")) == 1;
                    sessions.Add(rentalid, session);
                }

                if (!r.IsDBNull(r.GetOrdinal("genreid"))) {
                    sessions[rentalid].Movie.Genre.Add(
                        new GenreEntry { Id = r.GetInt32(r.GetOrdinal("genreid")), Name = r.GetString(r.GetOrdinal("genrename")) });
                }
            }
            r.Close();

            return sessions.Values.ToList();
        }

        public static List<RentSession> UserRentSessions(UserSession user, bool onlyActive, SqlHandler sh) {
            return UserRents(user.UserId, onlyActive, sh);
        }

        public static bool ActiveRent(int userId, int movieId, bool HD, SqlHandler sh) {
            var SQL = "SELECT userid "
                + "FROM rental "
                + "WHERE userid = @uid AND movieid = @mid AND hd = @hd "
                + "AND seendate >= GETDATE()";

            var c = sh.CreateCommand(SQL);
            c.Parameters.Add("uid", SqlDbType.Int).Value = userId;
            c.Parameters.Add("mid", SqlDbType.Int).Value = movieId;
            c.Parameters.Add("hd", SqlDbType.TinyInt).Value = HD ? 1 : 0;

            var r = c.ExecuteScalar();

            if(r is int) {
                return (int)r == userId;
            }
            return false;
        }
    }
}